package com.qmo.edu.base;

import android.os.Bundle;
import android.support.annotation.Nullable;

import com.qmo.edu.base.BaseActivity;
import com.qmo.edu.base.BasePresenter;
import com.qmo.edu.base.IBaseView;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.qmo.edu.mvp.factroy.IMvpPresenterFactroy;
import com.qmo.edu.mvp.factroy.IPresenterProxyFactroy;
import com.qmo.edu.mvp.factroy.MvpPresenterFactroyImpl;
import com.qmo.edu.mvp.factroy.PresenterProxyFactroyImpl;
import com.qmo.edu.widget.LoadingDialog;

import io.reactivex.ObservableTransformer;
import io.reactivex.subjects.PublishSubject;


public abstract class BaseMvpActivity<V extends IBaseView, P extends BasePresenter<V>> extends BaseActivity

        implements IPresenterProxyFactroy<V, P>, IBaseView {


    private static final String PRESENTER_SAVE_KEY = "presenter_save_key";
    protected final PublishSubject<ActivityEvent> lifecycleSubject = PublishSubject.create();

    /**
     * 绑定生命周期
     */
    @Override
    public <T> ObservableTransformer<T, T> bindLifeycle() {
        return this.bindToLifecycle();
    }


    /**
     * 创建被代理对象,传入默认Presenter的工厂
     */
    private PresenterProxyFactroyImpl<V, P> mProxy = new PresenterProxyFactroyImpl<>(MvpPresenterFactroyImpl.<V, P>creater(getClass()));
    private LoadingDialog mLoadingDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        mProxy.onCreate((V) this);
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            mProxy.onRestoreInstanceState(savedInstanceState.getBundle(PRESENTER_SAVE_KEY));
        }
        mLoadingDialog = new LoadingDialog(this);
        lifecycleSubject.onNext(ActivityEvent.CREATE);


    }

    @Override
    protected void onResume() {
        super.onResume();
        lifecycleSubject.onNext(ActivityEvent.RESUME);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mProxy.onDestroy();
        lifecycleSubject.onNext(ActivityEvent.DESTROY);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putBundle(PRESENTER_SAVE_KEY, mProxy.onSaveInstanceState());
    }

    @Override
    public void setPresenterFactory(IMvpPresenterFactroy<V, P> presenterFactory) {

        mProxy.setPresenterFactory(presenterFactory);
    }

    @Override
    public IMvpPresenterFactroy<V, P> getPresenterFactory() {

        return mProxy.getPresenterFactory();
    }

    @Override
    public P getMvpPresenter() {

        return mProxy.getMvpPresenter();
    }


    @Override
    public void showLoading() {
        if (mLoadingDialog != null) {
            mLoadingDialog.show();
        }
    }

    @Override
    public void hideLoading() {
        if (mLoadingDialog != null) {
            mLoadingDialog.dismiss();
        }
    }

}
